package com.sangeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sangeng.constants.SystemConstants;
import com.sangeng.domain.entity.LoginUser;
import com.sangeng.domain.entity.User;
import com.sangeng.mapper.UserMapper;
import com.sangeng.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuService menuService;
    /**
     * 根据用户名查询数据库中的用户
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
        lqw.eq(User::getUserName,s);
        User user = userMapper.selectOne(lqw);
        //判断查询到的用户是否存在
        if(Objects.isNull(user)){
            //用户不存在抛出异常
            throw new RuntimeException("用户不存在");
        }
        //判断当前用户是否是管理员，是管理员应该封装相应的权限
        List<String> permissions=null;
        if(user.getType().equals(SystemConstants.USER_TYPE_IS_ADMIN)){
            //是管理员查询相应的权限
            permissions= menuService.selectPermsByUserId(user.getId());
        }
        //将结果封装成userDetails
        return new LoginUser(user,permissions);
    }
}
